from IPy import IP
import tkinter


def ipmask(strs=''):
    try:
        ip = IP(strs, make_net=True)
        info = {}
        info['IP/MASK'] = str(ip)
        info['MASK'] = str(IP(ip).strNormal(2).split('/')[1])
        info['LENGTH'] = ip.len()
        info['START'] = str(ip[0])
        info['END'] = str(ip[-1])
        ret = info
    except:
        ip = ''
        ret = '格式有误'
    return ret, ip


class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name

    def set_init_window(self):
        self.init_window_name.title("IP子网掩码计算器")
        self.init_window_name.geometry('500x610+500+100')
        self.init_window_name.attributes("-alpha", 0.95)
        self.ip_label = tkinter.Label(self.init_window_name, text="IP/MASK")
        self.ip_label.pack(fill=tkinter.X, side=tkinter.TOP)
        self.ip_text = tkinter.Entry(self.init_window_name)
        self.ip_text.pack(fill=tkinter.X, side=tkinter.TOP, )
        self.button = tkinter.Button(self.init_window_name, text="计算", width=13, command=self.trans)
        self.button.pack(fill=tkinter.Y, side=tkinter.TOP)
        self.result_data_Text = tkinter.Text(self.init_window_name)
        self.scroll = tkinter.Scrollbar()
        self.scroll.pack(side=tkinter.RIGHT, fill=tkinter.Y)
        self.scroll.config(command=self.result_data_Text.yview())
        self.result_data_Text.config(yscrollcommand=self.scroll.set)
        self.result_data_Text.pack(fill=tkinter.Y, side=tkinter.TOP, expand='yes')

    # 功能函数
    def trans(self):
        self.result_data_Text.delete(1.0, tkinter.END)
        strs = self.ip_text.get()
        info, ip = ipmask(strs)
        if 'MASK' in info:
            self.result_data_Text.insert(tkinter.END,'')
            for i in info:
                self.result_data_Text.insert(tkinter.END, '{:<10}{}'.format(i, info[i]))
            self.result_data_Text.insert(tkinter.END, ''.format('=' * 50))
        else:
            self.result_data_Text.insert(tkinter.END, info)

        if ip:
            if ip.len() > 65536:
                self.result_data_Text.insert(tkinter.END, '列表过大')
            else:
                for i in ip:
                    self.result_data_Text.insert(tkinter.END, str(i) + '')


def gui_start():
    init_window = tkinter.Tk()
    ZMJ_PORTAL = MY_GUI(init_window)
    ZMJ_PORTAL.set_init_window()
    init_window.mainloop()


gui_start()